<?php

namespace app\controller\api\module\game;

use app\controller\api\module\game\components\Room;
use app\controller\api\module\game\components\Match;
use app\controller\api\module\ReceptionBaseController;
use think\response\Json;

class Index extends ReceptionBaseController
{
    protected function initialize()
    {
        parent::initialize();
        Room::getInstance()->setConfig($this->userInfo);
        Match::getInstance()->setConfig($this->userInfo);
    }

    /**
     *  创建房间
     * @params token
     * @return Json
     */
    public function createRoom(): Json
    {
        $res = Room::getInstance()->create();
        return $this->response($res['msg'], $res['code'], $res['data'], $res['header']);
    }

    /**
     * 加入房间
     * @params token
     * @params room_id      房间ID
     * @return Json
     */
    public function enterRoom(): Json
    {
        $res = Room::getInstance()->enter(values('room_id'));
        return $this->response($res['msg'], $res['code'], $res['data'], $res['header']);
    }

    /**
     * 开始游戏
     * @params token
     * @params my_chess       我的棋子颜色
     * @params him_chess      对方的棋子颜色
     * @params him_uid        对方的UID
     * @return Json
     */
    public function startGame(): Json
    {
        $res = Room::getInstance()->start(values('my_chess', 0), values('opponent_chess', 0));
        return $this->response($res['msg'], $res['code'], $res['data'], $res['header']);
    }

    /**
     * 离开房间
     * @params token
     * @params room_id      房间ID
     * @params identity     当前用户在房间内的身份，1房主，2玩家
     * @return Json
     */
    public function exitRoom(): Json
    {
        $res = Room::getInstance()->exit();
        return $this->response($res['msg'], $res['code'], $res['data'], $res['header']);
    }


    /**
     *  记录比赛中的每一步落子
     * @params token
     * @params room_id      房间号
     * @params board         棋盘
     * @params outcome         棋局结果，1:uid胜, 2:平局, 3:opposite_uid胜
     * @params chess         落子的颜色，1:白棋，2:黑棋
     * @return Json
     */
    public function recordChessPosition(): Json
    {
        $res = Match::getInstance()->record(values('x', 0), values('y', 0));
        return $this->response($res['msg'], $res['code'], $res['data'], $res['header']);
    }

    /**
     * 处理棋局结果
     * @params token
     * @params room_id      房间号
     * @params outcome      赢家的棋子颜色，1:白棋，2:黑棋，3:平局
     * @return Json
     */
    public function endGame(): Json
    {
        $res = Match::getInstance()->result();
        return $this->response($res['msg'], $res['code'], $res['data'], $res['header']);
    }

    /**
     * 记录悔棋信息
     * @params token
     * @params room_id      房间号
     * @params board_md5    棋盘md5
     * @return Json
     */
    public function withdraw(): Json
    {
        $res = Match::getInstance()->withdraw();
        return $this->response($res['msg'], $res['code'], $res['data'], $res['header']);
    }

}